<script setup lang="tsx">
import { adminUserListApi, deleteAdminUserApi } from '@/api/user'
import type { AdminUserItem } from '@/api/user/types'
import Write from './components/Write.vue'
import { getRoleListApi } from '@/api/role'
import { ElButton } from 'element-plus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await adminUserListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await deleteAdminUserApi(unref(ids.value[0]))
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const roleList = ref([])

const getRoleList = async () => {
  const res = await getRoleListApi({})
  roleList.value = res.data?.list || []
  return res.data?.list?.map((v) => ({
    label: v.name,
    value: v.id
  }))
}
getRoleList()

const isDisabled = ref(true)

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'userName',
    label: t('userDemo.username'),
    form: {
      componentProps: {
        disabled: isDisabled
      },
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'password',
    label: t('userDemo.password'),
    form: {
      colProps: {
        span: 24
      }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'roleId',
    label: t('userDemo.role'),
    search: {
      component: 'Select',
      optionApi: async () => getRoleList()
    },
    form: {
      colProps: {
        span: 24
      },
      component: 'Select',
      optionApi: async () => getRoleList()
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as AdminUserItem
          const obj: any = roleList.value.find((v: any) => v.id === row.roleId)
          return (
            <>
              <span>{obj && obj.name}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'status',
    label: t('userDemo.status'),
    form: {
      colProps: {
        span: 24
      },
      component: 'Select',
      componentProps: {
        options: [
          {
            label: t('common.normal'),
            value: 0
          },
          {
            label: t('common.banned'),
            value: 1
          }
        ]
      }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'createTime',
    label: t('userDemo.createTime'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'lastLoginIp',
    label: t('userDemo.lastLoginIp'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'lastLoginTime',
    label: t('userDemo.lastLoginTime'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 120,
      slots: {
        default: (data: any) => {
          const row = data.row as AdminUserItem
          return (
            <>
              <ElButton
                v-hasPermi="POST /admin/user/update"
                type="primary"
                link
                onClick={() => action(row, 'edit')}
              >
                {t('exampleDemo.edit')}
              </ElButton>
              <ElButton
                v-hasPermi="POST /admin/user/delete/{id}"
                type="danger"
                link
                onClick={() => delData(row)}
              >
                {t('exampleDemo.del')}
              </ElButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { userName, roleId } = params
  currentPage.value = 1
  searchParams.value = {
    userName,
    userRole: roleId
  }
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<AdminUserItem>()
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  allSchemas.formSchema.at(1)!.hidden = false
  isDisabled.value = false
  // allSchemas.formSchema.at(0)!.disabled = false
  actionType.value = ''
}

const delLoading = ref(false)
const ids = ref<string[]>([])

const delData = async (row?: AdminUserItem) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.id]
    : elTableExpose?.getSelectionRows().map((v: AdminUserItem) => v.id) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: AdminUserItem, type: string) => {
  dialogTitle.value = t('exampleDemo.edit')
  actionType.value = type
  currentRow.value = { ...row }
  allSchemas.formSchema.at(1)!.hidden = true
  isDisabled.value = true
  // allSchemas.formSchema.at(0)!.disabled = true
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  saveLoading.value = true
  const write = unref(writeRef)
  const res = await write?.submit()
  saveLoading.value = false
  if (!res) {
    return
  }
  dialogVisible.value = false
  getList()
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
      />

      <div class="mb-10px">
        <ElButton v-hasPermi="'POST /admin/user/create'" type="primary" @click="AddAction">{{
          t('exampleDemo.add')
        }}</ElButton>
      </div>
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle" :maxHeight="200">
      <Write ref="writeRef" :form-schema="allSchemas.formSchema" :current-row="currentRow" />

      <template #footer>
        <ElButton type="primary" :loading="saveLoading" @click="save">
          {{ t('exampleDemo.save') }}
        </ElButton>
        <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
      </template>
    </Dialog>
  </div>
</template>
